package com.chenjiahao.kaiyanwan.ui.search

import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.graphics.Typeface
import android.os.Build
import android.transition.Fade
import android.transition.Transition
import android.transition.TransitionInflater
import android.transition.Visibility
import android.view.KeyEvent
import android.view.View
import android.view.animation.AnimationUtils
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chenjiahao.kaiyanwan.KaiYanApplication
import com.chenjiahao.kaiyanwan.R
import com.chenjiahao.kaiyanwan.base.BaseActivity
import com.chenjiahao.kaiyanwan.logic.exception.ExceptionHandle
import com.chenjiahao.kaiyanwan.logic.util.StatusBarUtil
import com.chenjiahao.kaiyanwan.logic.util.ViewAnimUtils
import com.chenjiahao.kaiyanwan.showToast
import com.google.android.flexbox.*
import com.hazz.kotlinmvp.mvp.model.bean.HomeBean
import kotlinx.android.synthetic.main.activity_search.*
import java.lang.Exception
import java.lang.StringBuilder

class SearchActivity : BaseActivity() {
    private var mTextTypeface: Typeface? = null
    private var keyWords: String? = null
    //是否加载更多
    private var loadingMore = false

    private val viewModel by lazy { ViewModelProvider(this).get(SearchViewModel::class.java) }
    val categoryDetailAdapter by lazy {
        CategoryDetailAdapter(
            this,
            viewModel.itemList,
            R.layout.item_category_detail
        )
    }
    private val mHotKeywordsAdapter by lazy {
        HotKeywordsAdapter(this, viewModel.stringList, R.layout.item_flow_text)
    }

    init {
        //细黑简体字体
        mTextTypeface = Typeface.createFromAsset(
            KaiYanApplication.context.assets,
            "fonts/FZLanTingHeiS-L-GB-Regular.TTF"
        )
    }


    override fun layoutId(): Int {
        return R.layout.activity_search
    }

    override fun initData() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setUpEnterAnimation() // 入场动画
            setUpExitAnimation() // 退场动画
        } else {
            setUpView()
        }
    }

    override fun initView() {
        showHotWordView()
        tv_title_tip.typeface = mTextTypeface
        tv_hot_search_words.typeface = mTextTypeface
        //初始化查询结果的 RecyclerView
        mRecyclerView_result.layoutManager = LinearLayoutManager(this)
        mRecyclerView_result.adapter = categoryDetailAdapter
        mLayoutStatusView = multipleStatusView
        //状态栏透明和间距处理
        StatusBarUtil.darkMode(this)
        StatusBarUtil.setPaddingSmart(this, toolbar)
        val flexBoxLayoutManager = FlexboxLayoutManager(this)
        flexBoxLayoutManager.flexWrap = FlexWrap.WRAP      //按正常方向换行
        flexBoxLayoutManager.flexDirection = FlexDirection.ROW   //主轴为水平方向，起点在左端
        flexBoxLayoutManager.alignItems = AlignItems.CENTER    //定义项目在副轴轴上如何对齐
        flexBoxLayoutManager.justifyContent = JustifyContent.SPACE_AROUND  //多个轴对齐方式
        mRecyclerView_hot.layoutManager = flexBoxLayoutManager
        mRecyclerView_hot.adapter = mHotKeywordsAdapter

    }

    override fun start() {
        viewModel.getHotData()
        tv_cancel.setOnClickListener { onBackPressed() }
        //实现自动加载
        mRecyclerView_result.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                val itemCount =
                    (mRecyclerView_result.layoutManager as LinearLayoutManager).itemCount
                val lastVisibleItem =
                    (mRecyclerView_result.layoutManager as LinearLayoutManager).findLastVisibleItemPosition()
                if (!loadingMore && lastVisibleItem == (itemCount - 1)) {
                    loadingMore = true
                    //加载更多
                    viewModel.requestMoreData()
                }
            }
        })
        //键盘的搜索按钮
        et_search_view.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    closeSoftKeyboard()
                    keyWords = et_search_view.text.toString().trim()
                    if (keyWords.isNullOrEmpty()) {
                        showToast("请输入你感兴趣的关键词")
                    } else {
                        viewModel.requestSearchData(keyWords!!)
                    }
                }
                return false
            }

        })

        viewModel.searchData.observe(this, Observer {
            val searchData = it.getOrNull()
            fab_circle.visibility = View.GONE
            if (searchData != null) {
                loadingMore = false
                hideHotWordView()
                tv_search_count.visibility = View.VISIBLE
                tv_search_count.text =
                    "-「${keyWords}」搜索结果共${searchData.total}个-"
                viewModel.itemList = searchData.itemList
                viewModel.nextPageUrl = searchData.nextPageUrl
                categoryDetailAdapter.addData(viewModel.itemList)
            } else {
                showError(
                    ExceptionHandle.handleException(it.exceptionOrNull() as Exception),
                    ExceptionHandle.errorCode
                )
            }
        })

        viewModel.IssueData.observe(this, Observer {
            val issueData = it.getOrNull()
            if (issueData != null) {
                loadingMore = false
                viewModel.nextPageUrl = issueData.nextPageUrl
                viewModel.itemList = issueData.itemList
                categoryDetailAdapter.addData(viewModel.itemList)
            } else {
                showError(
                    ExceptionHandle.handleException(it.exceptionOrNull() as Exception),
                    ExceptionHandle.errorCode
                )
            }
        })

        viewModel.hotData.observe(this, Observer {
            val hotData = it.getOrNull()
            if (hotData != null) {
                viewModel.stringList = hotData
                mHotKeywordsAdapter.mData = viewModel.stringList
                mHotKeywordsAdapter.notifyDataSetChanged()
            } else {
                showError(
                    ExceptionHandle.handleException(it.exceptionOrNull() as Exception),
                    ExceptionHandle.errorCode
                )
            }
        })

        mHotKeywordsAdapter.setOnTagItemClickListener {
            keyWords = it
            viewModel.requestSearchData(it)
        }


    }

    /**
     * 退场动画
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private fun setUpExitAnimation() {
        val fade = Fade()
        window.returnTransition = fade
        fade.duration = 300
    }

    /**
     * 进场动画
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private fun setUpEnterAnimation() {
        val transition = TransitionInflater.from(this)
            .inflateTransition(R.transition.arc_motion)
        window.sharedElementEnterTransition = transition
        transition.addListener(object : Transition.TransitionListener {
            override fun onTransitionStart(transition: Transition) {

            }

            override fun onTransitionEnd(transition: Transition) {
                transition.removeListener(this)
                animateRevealShow()
            }

            override fun onTransitionCancel(transition: Transition) {

            }

            override fun onTransitionPause(transition: Transition) {

            }

            override fun onTransitionResume(transition: Transition) {

            }
        })
    }

    private fun setUpView() {
        val animation = AnimationUtils.loadAnimation(this, android.R.anim.fade_in)
        animation.duration = 300
        rel_container.startAnimation(animation)
        rel_container.visibility = View.VISIBLE
        //打开软键盘
        openKeyBord(et_search_view, applicationContext)
    }

    override fun onBackPressed() {
        fab_circle.visibility = View.VISIBLE
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ViewAnimUtils.animateRevealHide(
                this, rel_frame,
                fab_circle.width / 2, R.color.backgroundColor,
                object : ViewAnimUtils.OnRevealAnimationListener {
                    override fun onRevealHide() {
                        defaultBackPressed()
                    }

                    override fun onRevealShow() {

                    }
                })
        } else {
            defaultBackPressed()
        }
    }

    // 默认回退
    private fun defaultBackPressed() {
        closeSoftKeyboard()
        super.onBackPressed()
    }

    /**
     * 关闭软件盘
     */
    private fun closeSoftKeyboard() {
        closeKeyBord(et_search_view, applicationContext)
    }


    /**
     * 展示动画
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private fun animateRevealShow() {
        ViewAnimUtils.animateRevealShow(
            this, rel_frame,
            fab_circle.width / 2, R.color.backgroundColor,
            object : ViewAnimUtils.OnRevealAnimationListener {
                override fun onRevealHide() {

                }

                override fun onRevealShow() {
                    setUpView()
                }
            })
    }


    /**
     * 隐藏热门关键字的 View
     */
    private fun hideHotWordView() {
        tv_title_tip.visibility = View.GONE
        tv_hot_search_words.visibility = View.GONE
        mRecyclerView_hot.visibility = View.GONE
        tv_search_count.visibility = View.VISIBLE
        multipleStatusView.visibility = View.VISIBLE
        mRecyclerView_result.visibility = View.VISIBLE
    }

    /**
     * 显示热门关键字的 流式布局
     */
    private fun showHotWordView() {
        tv_title_tip.visibility = View.VISIBLE
        tv_hot_search_words.visibility = View.VISIBLE
        mRecyclerView_hot.visibility = View.VISIBLE
        tv_search_count.visibility = View.GONE
        multipleStatusView.visibility = View.GONE
        mRecyclerView_result.visibility = View.GONE
    }


}
